//
//  addListTableViewController.m
//  ZPSALE
//
//  Created by tmosport on 14-6-5.
//  Copyright (c) 2014年 tmosport. All rights reserved.
//

#import "addListTableViewController.h"
#import "addAdressVC.h"
#import "MBProgressHUD.h"

@interface addListTableViewController ()
@property (nonatomic, retain) NSArray* logResult;
@property (nonatomic, assign) NSInteger delAddrId;
@end

@implementation addListTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self dataInit];
    [self setupTableView];
    [self setupNav];
}
-(void)setupNav
{
    self.title = @"收货地址";

    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]
                                             initWithTitle:@"添加"
                                             style:UIBarButtonItemStyleBordered
                                             target:self
                                             action:@selector(toAdd)];
    [self.navigationController.navigationBar setBackIndicatorImage:
     [UIImage imageNamed:@"return"]];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:
     [UIImage imageNamed:@"return"]];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
}

-(void)leftBarbuttonItemClicked:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupTableView
{
//    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
//    view.backgroundColor = [UIColor clearColor];
//    self.addrTV.tableFooterView = view;
}
-(void)viewWillAppear:(BOOL)animated
{
    [self dataInit];
}

- (void)dataInit{
    
    NSDictionary *params = @{@"memberid": _memberId,
                             @"access_token": _token,
                             };
    
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger GET:APIURL@"myzhenpin/getMyAddress.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        _logResult = (NSArray *)responseObject[@"result"];
        [self.addrTV reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //TODO
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [_logResult count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier = @"defaultCell";
    static NSString* otherCellIdentifier = @"otherCell";
    UITableViewCell *cell;
    NSDictionary *cellData = [_logResult objectAtIndex:indexPath.row];
    if ([cellData[@"isDefault"] isEqualToNumber:[NSNumber numberWithBool:YES]]) {
        cell = nil;
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        }
        cell.backgroundColor = RGB(255,68,0);
        UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:1];
        UILabel *mobile = (UILabel *)[cell.contentView viewWithTag:2];
        UILabel *address = (UILabel *)[cell.contentView viewWithTag:3];
        UIButton *editBT = (UIButton *)[cell.contentView viewWithTag:4];
        UIButton *delBT = (UIButton *)[cell.contentView viewWithTag:5];
        editBT.tag = indexPath.row;
        delBT.tag = [cellData[@"addrId"] intValue];
        [editBT setImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
        [editBT setImageEdgeInsets:UIEdgeInsetsMake(0.0, -10, 0.0, 0.0)];
        [editBT setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        //    editBT.tag = [cellData[@"addrId"] intValue] ;
        [delBT setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
        [delBT setImageEdgeInsets:UIEdgeInsetsMake(0.0, -10, 0.0, 0.0)];
        [delBT addTarget:self action:@selector(del:) forControlEvents:UIControlEventTouchUpInside];
        [delBT setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        nameLabel.text = cellData[@"receiver"];
        mobile.text = cellData[@"phone"];
        NSString *addString = [NSString stringWithFormat:@"%@%@%@ %@",cellData[@"province"],cellData[@"city"],cellData[@"town"],cellData[@"address"]];
        address.text = addString;
        cell.tag = indexPath.row;
    }else{
        cell = nil;
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:otherCellIdentifier];
        }
        cell.backgroundColor = ColorFromRGB(0xffffff);
        UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:1];
        UILabel *mobile = (UILabel *)[cell.contentView viewWithTag:2];
        UILabel *address = (UILabel *)[cell.contentView viewWithTag:3];
        UIButton *editBT = (UIButton *)[cell.contentView viewWithTag:4];
        UIButton *delBT = (UIButton *)[cell.contentView viewWithTag:5];
        editBT.tag = indexPath.row;
        delBT.tag = [cellData[@"addrId"] intValue];
        [editBT setImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
        [editBT setTitle:@"编辑" forState:UIControlStateNormal];
        [editBT setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [editBT setImageEdgeInsets:UIEdgeInsetsMake(0.0, -10, 0.0, 0.0)];
        [delBT setTitle:@"删除" forState:UIControlStateNormal];
        [delBT setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [delBT setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
        [delBT setImageEdgeInsets:UIEdgeInsetsMake(0.0, -10, 0.0, 0.0)];
        [delBT addTarget:self action:@selector(del:) forControlEvents:UIControlEventTouchUpInside];
        nameLabel.textColor = ColorFromRGB(0x333333);
        address.textColor = ColorFromRGB(0x333333);
        mobile.textColor = ColorFromRGB(0x333333);
        nameLabel.text = cellData[@"receiver"];
        mobile.text = cellData[@"phone"];
        NSString *addString = [NSString stringWithFormat:@"%@%@%@ %@",cellData[@"province"],cellData[@"city"],cellData[@"town"],cellData[@"address"]];
        address.text = addString;
        cell.tag = indexPath.row;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *cellData = [_logResult objectAtIndex:indexPath.row];
    NSInteger _updateAddrId = [cellData[@"addrId"] intValue];
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.dimBackground = YES;
    HUD.labelText = @"设置默认地址";
    NSNumber *addrId = [NSNumber numberWithInteger:_updateAddrId];
        NSDictionary *params = @{@"memberid": _memberId,
                                 @"access_token": _token,
                                 @"addrId": addrId
                                 };
        AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
        [manger POST:APIURL@"myzhenpin/updateAddressIsDefault.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ((NSDictionary *)responseObject[@"result"]) {
                //(@"默认地址");
                [HUD showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                    HUD.mode = MBProgressHUDModeText;
                    HUD.labelText = @"更新成功!";
                }completionBlock:^{
                    sleep(1);
                    [HUD hide:YES afterDelay:3];
                }];
            } ;
            [self dataInit];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //TODO
        }];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UIButton *)sender
{
    if ([segue.identifier isEqual:@"addAddr"]) {
        addAdressVC *destVC = segue.destinationViewController;
        destVC.addrId  = 0;
        destVC.memberId =  _memberId;
        destVC.token = _token;
    }else{
    addAdressVC *destVC = segue.destinationViewController;
    NSInteger tag = sender.tag;
    NSDictionary *cellData = [_logResult objectAtIndex:tag];
    destVC.addrId  = [cellData[@"addrId"] intValue];
    destVC.memberId =  _memberId;
    destVC.token = _token;
    }
}

- (void)toAdd
{
        addAdressVC *destVC = [self.storyboard instantiateViewControllerWithIdentifier:@"addAdressVC"];
        destVC.addrId  = 0;
        destVC.memberId =  _memberId;
        destVC.token = _token;
    [self.navigationController pushViewController:destVC animated:YES];
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 1)];
    [view setBackgroundColor:[UIColor clearColor]];
    return view;
}

-(void)del:(UIButton *)button
{
    _delAddrId = button.tag;
    if (_delAddrId > 0 ) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"确认删除当前地址?"
                                                                delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles: nil];
        [actionSheet showInView:self.view];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSNumber *addrId = [NSNumber numberWithInteger:_delAddrId];
        NSDictionary *params = @{@"memberid": _memberId,
                                 @"access_token": _token,
                                 @"addrid": addrId
                                 };
        AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
        [manger POST:APIURL@"myzhenpin/delThisAddr.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //        if ((NSDictionary *)responseObject[@"result"]) {
            //            //DO:删除结果判断
            //        };
            [self dataInit];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //TODO
        }];
    }
}
@end
